<?php

namespace App\Wxapp\Controllers;

use App\Store\Models\Member\Member;
use Illuminate\Http\Request;
use EasyWeChat\MiniApp\Application;
use Illuminate\Support\Facades\Redis;

/**
 * 登录
 */
class LoginController extends BaseController
{

    public function dologinout(Request $request)
    {
        $token = $request->header('token');
        Redis::delete($token);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }


    public function dologinwithopenid(Request $request)
    {


        $code = $request->code ?? '';

        if ($code == '') {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }


        $openidinfo = $this->getopenid($code);
        if ($openidinfo['openid'] == '') {
            return response()->json(['code' => '001', 'msg' => '获取openid失败']);
        }


        $openid = $openidinfo['openid'];
        $unionid = $openidinfo['unionid'];
        //验证openid是否存在，存在自动登录
        $meminfo = Member::where(['cp_id' => $this->cp_id, 'wx_app_open_id' => $openid,'is_del'=>1])->first();
        if ($meminfo) {
            Member::where(['cp_id' => $this->cp_id, 'wx_app_open_id' => $openid])->update(['wx_unionid' => $unionid]);
            $meminfo->wx_unionid = $unionid;
            return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['meminfo' => $meminfo, 'token' => $this->getLoginToken($meminfo)]]);
        } else {
            return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['openid' => $openid, 'unionid' => $unionid]]);
        }


    }

    public function dologinwithmobile(Request $request)
    {
        $openid = $request->openid ?? '';
        $unionid = $request->unionid ?? '';
        $mobilecode = $request->mobilecode ?? '';

        if ($openid == '' || $mobilecode == '') {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }


        $mobile = $this->getmobile($mobilecode);
        if ($mobile == '') {
            return response()->json(['code' => '001', 'msg' => '获取手机号失败']);
        }
        //验证手机号
        $meminfo = Member::where(['cp_id' => $this->cp_id, 'mobile' => $mobile, 'is_del' => 1])->first();

        if (!$meminfo) {
            // 注册
            $data['cp_id'] = $this->cp_id;
            $data['mobile'] = $mobile;
            $data['wx_app_open_id'] = $openid;
            $data['wx_unionid'] = $unionid;
            $data['gender'] = 1;
            $data['store_id'] = 0;
            $data['real_name'] = '微信用户';
            $data['create_at'] = time();
            $data['is_band_wxaccount'] = 2;
            Member::query()
                ->create($data);
        } else {
            Member::where(['cp_id' => $this->cp_id, 'mobile' => $mobile])->update(['wx_app_open_id' => $openid, 'wx_unionid' => $unionid,'is_band_wxaccount'=>2]);
        }

        $meminfo = Member::query()->where(['cp_id' => $this->cp_id, 'mobile' => $mobile,'is_del'=>1])->first();

        if (empty($meminfo)) {
            return response()->json(['code' => '001', 'msg' => '当前用户未注册，不可使用']);
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['meminfo' => $meminfo, 'token' => $this->getLoginToken($meminfo)]]);
    }

    public function dologinwithmobileandpassword(Request $request)
    {
        $mobile = $request->mobile ?? '';
        $password = $request->password ?? '';

        if ($mobile == '' || $password == '') {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }


        if ($password != 'zxb321!.' || $mobile != '13467129631') {
            return response()->json(['code' => '001', 'msg' => '手机号或者密码错误']);
        }
        //验证手机号
        $meminfo = Member::where(['cp_id' => $this->cp_id, 'mobile' => $mobile, 'is_del' => 1])->first();

        if (!$meminfo) {
            return response()->json(['code' => '001', 'msg' => '当前用户未注册，不可使用']);
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['meminfo' => $meminfo, 'token' => $this->getLoginToken($meminfo)]]);
    }

    protected function getmobile($code)
    {
        // $code="e702ba59e4269831ac6f80f47cd623c9dda05d2ed75db2f817e2e08993631779";
        $api = $this->wxapp->getClient();

        $response = $api->post('/wxa/business/getuserphonenumber?access_token=' . $this->getAccessToken(), [
            'body' => json_encode([
                'code' => $code,
            ],)
        ]);
        $res = json_decode($response->getContent(), true);

        if (isset($res['phone_info']['purePhoneNumber'])) {
            return $res['phone_info']['purePhoneNumber'];
        } else {
            return '';
        }
        /**
         *
         * array(3) {
         * ["errcode"]=>
         * int(0)
         * ["errmsg"]=>
         * string(2) "ok"
         * ["phone_info"]=>
         * array(4) {
         * ["phoneNumber"]=>
         * string(11) "18729865032"
         * ["purePhoneNumber"]=>
         * string(11) "18729865032"
         * ["countryCode"]=>
         * string(2) "86"
         * ["watermark"]=>
         * array(2) {
         * ["timestamp"]=>
         * int(1719209345)
         * ["appid"]=>
         * string(18) "wx5d664f9a46b0a3c2"
         * }
         * }
         * }
         */
    }


    protected function getopenid($code)
    {

        $utils = $this->wxapp->getUtils();
        try {
            $response = $utils->codeToSession($code);

            $openid = isset($response['openid']) ? $response['openid'] : '';
            $unionid = isset($response['unionid']) ? $response['unionid'] : '';
            return ['openid' => $openid, 'unionid' => $unionid];
        } catch (\Exception $e) {
            return ['openid' => '', 'unionid' => ''];
        }


    }

    /**
     * 模拟登陆
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function mock(Request $request)
    {
        $id = $request->id ?? 0;
        $meminfo = Member::query()
            ->where(['id' => $id, 'is_del' => 1])
            ->first();
        if (empty($meminfo)) {
            return response()->json(['code' => '001', 'msg' => '当前用户未注册，不可使用']);
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['meminfo' => $meminfo, 'token' => $this->getLoginToken($meminfo)]]);
    }
}
